<template>
  <el-form
    ref="form"
    :model="passwordForm"
    :rules="rules"
    label-width="120px"
  >
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input
        v-model="passwordForm.oldPassword"
        placeholder="请输入旧密码"
        type="password"
        show-password
      />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input
        v-model="passwordForm.newPassword"
        placeholder="请输入新密码"
        type="password"
        show-password
      />
    </el-form-item>
    <el-form-item label="确认新密码" prop="confirmPassword">
      <el-input
        v-model="passwordForm.confirmPassword"
        placeholder="请再次输入新密码"
        type="password"
        show-password
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button @click="reset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { changePassword } from '@/api/user'
import { resetRouter } from '@/router'

export default {
  name: 'ResetPwd',
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '旧密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '旧密码长度必须在6到20个字符之间', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '新密码长度必须在6到20个字符之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          changePassword({
            old_password: this.passwordForm.oldPassword,
            password: this.passwordForm.newPassword
          }).then(() => {
            this.$message.success('密码修改成功，请重新登录')
            // 退出登录，重定向到登录页面
            this.$store.dispatch('user/logout')
            resetRouter()
            this.$router.push(`/login?redirect=${this.$route.fullPath}`)
          })
        }
      })
    },
    reset() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      this.$refs.form.resetFields()
    }
  }
}
</script> 